/**
 * 异步路由加载,需要在main.js中引用
 */
import router from "@/router";
import {Message} from "element-ui";
import store from '@/store'
//vue中引用 NProgress
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

NProgress.inc(0.9)
NProgress.configure({easing: 'ease', speed: 500, showSpinner: false})

router.beforeEach(((to, from, next) => {
    NProgress.start()
    // to 表示将要访问的路径
    // from 表示从哪个路径跳转过来
    // next 是一个函数，表示放行
    // next() 表示直接放行  next('/xxx')表示强制跳转
    // 显示meta.的title数据
    if (to.meta.title) {
        document.title = to.meta.title == null || undefined ? "首页" : to.meta.title
    }
    if (to.path === "/" || to.path === "/login") {
        return next()
    } else {
        if (window.sessionStorage.getItem("user")) {
            store.commit("SET_ACTIVE_PATH", to.path)
            if (store.state.routes.length > 0) {
                return next();
            } else {
                // 发送请求获取路由数据
                store.dispatch("getRoutes").then(res => {
                    router.addRoutes(res) // 动态添加可访问路由表
                    return next({...to, replace: true}) // 确保router.addRoutes添加完成路由之后,在完成跳转操作
                })
            }
        } else {
            Message.error("您尚未登录,即将跳转登录页~")
            store.commit("SET_ACTIVE_PATH", to.path)
            return next("/login?redirect=" + to.path)
        }
    }
}))

router.afterEach((to, from) => {
    NProgress.done();
    // console.log("afterEach , from ", from)
    // console.log("afterEach ,too", to)
})
